﻿using System;
using ValidationEngine.Commons;
using ValidationEngine.Commons.Enums;
using ValidationEngine.Commons.Interfaces;
using ValidationEngine.Tools;

namespace ValidationEngine.ValidationRules
{
    public class CompareStringValueRule : BaseValidationRule
    {
        #region Members
        private readonly object _valueToCompareWith;
        private readonly bool _shouldMatch;
        #endregion

        protected override IValidationInfo ApplyRule(IValidationContext ctx)
        {
            if (_shouldMatch)
            {
                DefResult = ModelHelper.GetPropertyValue(ctx).ToString().Equals(_valueToCompareWith) ? null : _defErrorMsg;
            }
            else
            {
                DefResult = !ModelHelper.GetPropertyValue(ctx).ToString().Equals(_valueToCompareWith) ? null : _defErrorMsg;
            }

            return Result;
        }

        #region Ctor
        public CompareStringValueRule(
           string etalon,
           bool shouldMatch = true,
           string defErrorText = null,
           RuleApplingContext applyCxt = RuleApplingContext.Always,
           ValidationErrorType errorType = ValidationErrorType.Error)
        {
            this._valueToCompareWith = etalon;
            this.ApplingContext = applyCxt;
            this._defErrorType = errorType;
            this._shouldMatch = shouldMatch;
            this._defErrorMsg = defErrorText ?? String.Format("Should {0} match value: {1}", _shouldMatch ? "" : "not", etalon);
        }
        #endregion
    }
}
